package com.bruce.downloader.handle;

import com.bruce.downloader.print.SimpleDownloadProcessInfo;
import org.springframework.http.client.ClientHttpResponse;

import java.io.*;

/**
 * 文件响应器
 * <br>CreateDate  2021/09/15 17:31:07
 *
 * @author luotuan
 * @version 1.0.0
 */
public class FileResponseExtractor extends AbstractResponseExtractor<File> {
    private String dirFilePath;
    private int index;

    public FileResponseExtractor(String dirFilePath,int index) {
        this.dirFilePath = dirFilePath;
        this.index = index;
    }

    public FileResponseExtractor(String dirFilePath) {
        this.dirFilePath = dirFilePath;
    }

    /**
     * 数据处理
     *
     * @param clientHttpResponse 客户端http响应
     * @return 文件
     * <br>CreateDate 2021/09/15 17:30:02
     * @author luotuan
     * @since 1.0.0
     **/
    @Override
    protected File doExtractData(ClientHttpResponse clientHttpResponse) throws IOException {
        File file = new File(dirFilePath);
        try (
                InputStream inputStream = clientHttpResponse.getBody();
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))
        ) {
            int len;
            while ((len = bis.read(BYTE)) != -1) {
                SimpleDownloadProcessInfo.getDownSize().add(len);
                bos.write(BYTE, 0, len);
            }
        }
        return file;
    }

    public String getDirFilePath() {
        return dirFilePath;
    }

    public FileResponseExtractor setDirFilePath(String dirFilePath) {
        this.dirFilePath = dirFilePath;
        return this;
    }

    public int getIndex() {
        return index;
    }

    public FileResponseExtractor setIndex(int index) {
        this.index = index;
        return this;
    }
}
